<?php

namespace app\service;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use Darabonba\OpenApi\Models\Config;
use think\facade\Lang;

class AliSmsService
{
    /**
     * 使用AK&SK初始化账号Client.
     *
     * @return Dysmsapi Client
     */
    public static function createClient()
    {
        $aliSmsConfig = config('app.ali_sms');
        $config = new Config([
            'accessKeyId' => $aliSmsConfig['accessKeyId'],
            'accessKeySecret' => $aliSmsConfig['AccessKeySecret'],
            'protocol' => 'http',
        ]);
        // 访问的域名
        $config->endpoint = 'dysmsapi.aliyuncs.com';

        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     *
     * @return void
     */
    public static function main($args)
    {
        $client = self::createClient();
        $aliSmsConfig = config('app.ali_sms');
        $sendSmsRequest = new SendSmsRequest([
            'signName' => $aliSmsConfig['signName'],
            'phoneNumbers' => $args['phone'],
            'templateCode' => $args['template'],
            'templateParam' => $args['params'],
        ]);

        // 发送短信并获取响应
        $res = $client->sendSms($sendSmsRequest);

        // 根据阿里云返回状态判断是否成功
        if ($res->body->code == 'OK') {
            return true;
        }

        return false;
    }
}
